package com.mgm.controller.api;

import java.io.IOException;
import java.net.URI;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.mgm.advertisement.service.AdvertisementService;
import com.mgm.advertiser.service.AdvertiserService;
import com.mgm.click.service.ClickInfoService;
import com.mgm.constant.GobalConstant;
import com.mgm.pojo.Advertisement;
import com.mgm.pojo.ClickInfo;
import com.mgm.utils.IPUtil;
import com.mgm.utils.RandomCodeUtils;

/**
 * 下游offer点击调用接口
 * @ClassName: ClickController 
 * @Description: 下游广告被流量点击后会通知该接口
 * @author Andy Zhang
 * @date 2018年8月30日 下午5:07:08 
 * 二级域名：click.moboair.net 
 */
@Controller
@RequestMapping("/api")
public class ClickController {
	
	private static Logger logger =LoggerFactory.getLogger(ClickController.class);
	@Autowired 
	private ClickInfoService clickInfoService;
	@Autowired 
	private AdvertisementService advertisementService;
	@Autowired 
	private AdvertiserService advertiserService;
	
	/**
	 * 此接口统一处理下游渠道点击事件
	 * @Title: receiveClick   
	 * @Description: 处理clickurl
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ModelAndView      
	 * @throws
	 */
	//https://moboair.net/v1/click?offid=1532419819724&affid=aff3514&tid={transaction_id}&pkgname={pkgname}&subaffid={subaffid}&idfa={idfa}&gaid={gaid}&aid={aid}&data1={data1}&data2={data2}&data3={data3}&data4={data4}
	@RequestMapping(value="/v1/click", method = RequestMethod.GET)
	public ModelAndView receiveClick(@RequestParam(value="offid", required=true) String offid,
			@RequestParam(value="affid", required=true) String affid, @RequestParam(value="tid", required=true) String tid,
			@RequestParam(value="pkgname", required=false) String pkgname, @RequestParam(value="subaffid", required=false) String subaffid,
			HttpServletRequest request, HttpServletResponse response) {
		//先获取来源地址（Header中的referer来源）
		logger.info("【Click 来源】 from Referer URL ： {}", request.getHeader("Referer"));
		String clickUrl = request.getRequestURL() + "?" + request.getQueryString();
		logger.info("【Click URL】 from Click URL ： {}", clickUrl);
		Date curTime = new Date();
		request.getHeaderNames();
		
		ClickInfo clickInfo = new ClickInfo();//constructClickInfo(request);
		clickInfo.setClickUrl(clickUrl);
		clickInfo.setClickat(curTime); //当前时间
		clickInfo.setOfferid(offid);
		clickInfo.setAffid(affid);
		clickInfo.setPkgname(StringUtils.isEmpty(pkgname)||"{pkgname}".equals(pkgname) ? null : pkgname);
		clickInfo.setAfftid(tid); //这存渠道tid, tid存的是MGM tid
		String mgmTid = System.currentTimeMillis()+clickInfo.getAffid().substring(GobalConstant.AFF_PRE.length())+RandomCodeUtils.randomNumeric(4); //系统生成Tid
		clickInfo.setTid(mgmTid); //MGM的tid
		clickInfo.setSubaffid(StringUtils.isEmpty(pkgname)||"{subaffid}".equals(subaffid) ? affid : subaffid); //子渠道(空为本身自己)
		
		clickInfo.setIp(IPUtil.getClientIp(request));
		clickInfo.setRefer(StringUtils.isEmpty(request.getHeader("Referer")) ? null : request.getHeader("Referer"));
		clickInfo.setUserAngent(StringUtils.isEmpty(request.getHeader("User-Agent")) ? null : request.getHeader("User-Agent"));
		
		clickInfo.setIdfa(StringUtils.isEmpty(request.getParameter("idfa"))||"{idfa}".equals(request.getParameter("idfa")) ? null : request.getParameter("idfa"));
		clickInfo.setGaid(StringUtils.isEmpty(request.getParameter("gaid"))||"{gaid}".equals(request.getParameter("gaid")) ? null : request.getParameter("gaid"));
		clickInfo.setAid(StringUtils.isEmpty(request.getParameter("aid"))||"{aid}".equals(request.getParameter("aid")) ? null : request.getParameter("aid"));
		//TODO set data1-data4...
		clickInfo.setD1(StringUtils.isEmpty(request.getParameter("data1"))||"{data1}".equals(request.getParameter("data1")) ? null : request.getParameter("data1"));
		clickInfo.setD2(StringUtils.isEmpty(request.getParameter("data2"))||"{data2}".equals(request.getParameter("data2")) ? null : request.getParameter("data2"));
		clickInfo.setD3(StringUtils.isEmpty(request.getParameter("data3"))||"{data3}".equals(request.getParameter("data3")) ? null : request.getParameter("data3"));
		clickInfo.setD4(StringUtils.isEmpty(request.getParameter("data4"))||"{data4}".equals(request.getParameter("data4")) ? null : request.getParameter("data4"));
		clickInfo.setCode(GobalConstant.CLICK_SUCCESS+""); //默认成功
		
		String redirectUrl = transformRedirectUrl(clickInfo); //转换链接302跳转
		clickInfo.setRedirectUrl(redirectUrl);
		clickInfoService.saveClickInfo(clickInfo); //入库
		
//		HttpConnectionUtil.doGetAsyn(redirectUrl, callBack);
//		String returnResult = doGet(redirectUrl, request, null);
//		logger.info("【Click 302 跳转】redirect url : {}, 返回结果：{}", redirectUrl, returnResult);
		
		ModelAndView view = new ModelAndView();
		view.setViewName("redirect:"+redirectUrl); //第二种方式
		return view; //302跳转
		
	}
	
	/**
	 * 构造clickurl,实现302跳转到上游
	 * @Title: generalRedirectUrl   
	 * @Description: 粗暴替换宏...   
	 * @param: @param clickInfo
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	private String transformRedirectUrl(ClickInfo clickInfo) {
		Advertisement ad = advertisementService.findByOfferId(clickInfo.getOfferid());
		String clickurl = ad.getClick_url();
		if(clickurl.contains("apptrknow.com")) { //Clickdealer的clickurl
//			http://apptrknow.com/dir/redirect?placement_id=10219&campaign_id=35888325&affid=8732&cid=[cid]
//				&data1=[data1]&data2=[data2]&data3=[data3]&data4=[data4]
//						&affsub1=[affsub1]&device_id=[device_id]&idfa=[idfa]&gaid=[gaid]&source_app=[source_app]&creative_id=[creative_id]
			Map<String, String> map = new HashMap<>();
			map.put("[cid]", clickInfo.getTid()); //MGM的tid
			map.put("[data1]", clickInfo.getD1()==null ? "" : clickInfo.getD1());
			map.put("[data2]", clickInfo.getD2()==null ? "" : clickInfo.getD2());
			map.put("[data3]", clickInfo.getD3()==null ? "" : clickInfo.getD3());
			map.put("[data4]", clickInfo.getD4()==null ? "" : clickInfo.getD4());
			map.put("[affsub1]", clickInfo.getSubaffid());
			map.put("[device_id]", clickInfo.getAid()==null ? "" : clickInfo.getAid());
			map.put("[idfa]", clickInfo.getIdfa()==null ? "" : clickInfo.getIdfa());
			map.put("[gaid]", clickInfo.getGaid()==null ? "" : clickInfo.getGaid());
			map.put("[source_app]", ""); //下游投放时的APP名，选填
			map.put("[creative_id]", ""); //选填
			for (String key : map.keySet()) {
				clickurl = clickurl.replace(key, map.get(key)==null ? "" : map.get(key));
			}
		} else if (clickurl.contains("tracking.adkmob.com")) { //Cheetah的clickurl
			/*http://tracking.adkmob.com/click/11038/10861277/
			 * ?tid={transaction_id}&gaid={advertising_id}&aid={android_id}&sub1={sub1}&sub2={sub2}&sub3={sub3}&sub4={sub4}&sub5={sub5}&sub6={sub6}
			 * &pub_id={pub_id}&sub_id={sub_id}&bundle={bundle}&creative_name={creative_name}&per={permission}&flag=2fb62edf054d814e17965ed06870f75d
			 */	
			Map<String, String> map = new HashMap<>();
			map.put("{transaction_id}", clickInfo.getTid()); //MGM的tid
			map.put("{advertising_id}", clickInfo.getGaid()==null ? "" : clickInfo.getGaid());
			map.put("{android_id}", clickInfo.getAid());
			map.put("{sub1}", "");
			map.put("{sub2}", "");
			map.put("{sub3}", "");
			map.put("{sub4}", "");
			map.put("{sub5}", "");
			map.put("{sub6}", "");
			map.put("{pub_id}", clickInfo.getAffid()==null ? "" : clickInfo.getAffid()); //猎豹-换成我们下游渠道id
			map.put("{sub_id}", clickInfo.getSubaffid()==null ? "" : clickInfo.getSubaffid()); //猎豹-下游的子渠道
			map.put("{bundle}", clickInfo.getPkgname()==null ? "" : clickInfo.getPkgname());
			map.put("{creative_name}", "");
			map.put("{permission}", clickInfo.getGaid()==null ? "" : clickInfo.getGaid());
			for (String key : map.keySet()) {
				clickurl = clickurl.replace(key, map.get(key)==null ? "" : map.get(key));
			}
		} else if (clickurl.contains("ads.mobpals.com") || clickurl.contains("testclick.mobpals.com")) { //Mobpals的clikurl 
		/*
		 * (默认："http://ads.mobpals.com/acs.php?sid=5592&adid=3134285" 
		 * + &gaid={gaid}&idfa={idfa}&clickid={click id}&osv={os version}&subid={subid}&aff_sub1={aff_sub1}&aff_sub2={aff_sub2} )
		 */
			if(!StringUtils.isEmpty(clickInfo.getGaid())) {
				clickurl += "&gaid="+clickInfo.getGaid();
			}
			if(!StringUtils.isEmpty(clickInfo.getIdfa())) {
				clickurl += "&idfa="+clickInfo.getIdfa();
			}
			clickurl += "&clickid="+clickInfo.getTid();
			clickurl += "&subid="+clickInfo.getSubaffid();
		} else if (clickurl.contains("apps.applift.com")) { //Applift
			Map<String, String> map = new HashMap<>();
			map.put("{click_id}", clickInfo.getTid()); //MGM的tid
			map.put("{gaid}", clickInfo.getGaid()==null ? "" : clickInfo.getGaid());
			map.put("{idfa}", clickInfo.getIdfa()==null ? "" : clickInfo.getIdfa());
			map.put("{aid}", clickInfo.getAid()==null ? "" : clickInfo.getAid());
			map.put("{sub publisher id}", clickInfo.getSubaffid()==null ? "" : clickInfo.getSubaffid());
			
			for (String key : map.keySet()) {
				clickurl = clickurl.replace(key, map.get(key)==null ? "" : map.get(key));
			}
		}
		return clickurl;
	}
	
	
	public String doGet(String url, HttpServletRequest request, Map<String, String> param) {

		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			
//			httpGet.setHeader("User-Agent", request.getHeader("User-Agent"));
//			httpGet.setHeader("Referer", request.getHeader("Referer"));
//			httpGet.setHeader("HTTP_CLIENT_IP", IPUtil.getClientIp(request));

			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
}
